package com.example;

import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: fransvanderlek
 * Date: 6/17/12
 * Time: 11:03 AM
 * To change this template use File | Settings | File Templates.
 */
public class ScanFilesTask extends SynchronizationTask {

    private File localDirectory;


    public ScanFilesTask(MainViewHolder view, File localDirectory, FTPClient ftpClient) {
        super(view, ftpClient);
        this.localDirectory = localDirectory;
    }

    @Override
    protected List<File> doInBackground(List<File>... lists) {

        List<File> pendingFiles = lists[0];

        try {


            String[] remoteFiles = ftpClient.listNames();

            if (remoteFiles == null) {
                remoteFiles = new String[0];
            }

            List<File> localFiles = Arrays.asList(this.localDirectory.listFiles());

            for (File file : localFiles) {
                boolean add = true;

                for (String remoteFileName : remoteFiles) {

                    if (remoteFileName.equals(file.getName())) {
                        add = false;
                    }
                }

                if ( add){
                    pendingFiles.add(file);
                    publishProgress(pendingFiles);
                }
            }

        } catch (Exception e) {

            // view.messagesView.setText("Got error while scanning: " + e.getMessage());

        } finally {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                //  view.messagesView.setText("Got error while disconnecting: " + e.getMessage());
            }
        }
        return pendingFiles;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    protected void onPostExecute(List<File> files) {

        super.onPostExecute(files);

        if (files.isEmpty()) {
            view.messagesView.setText("No files to synch.");
        }

    }
}
